package cn.com.bluemoon.daps.standard.excel;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataModel;
import cn.afterturn.easypoi.handler.inter.IExcelModel;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jarod.Kong
 * @date 2020/8/27 9:03
 */
@Slf4j
public final class ExcelImportResultUtils {
    private ExcelImportResultUtils(){};
    /**
     * 针对标准抽取的导入方法
     *
     * @param filePath
     * @param verifyHandler
     * @param clz
     * @param sheetIndexFrom
     * @param sheetNum
     * @param titleRow
     * @param verifyGroups
     * @param <T>
     * @return
     */
    public static <T> ExcelImportResult<T> excelImportResult(String filePath,
                                                             IExcelVerifyHandler<T> verifyHandler,
                                                             Class<T> clz,
                                                             int sheetIndexFrom,
                                                             int sheetNum,
                                                             int titleRow,
                                                             Class<?>[] verifyGroups) {
        ImportParams params = new ImportParams();
        if (verifyHandler != null || verifyGroups != null) {
            params.setNeedVerify(true);
            if (verifyGroups != null && verifyGroups.length > 0) {
                params.setVerifyGroup(verifyGroups);
            }
        }
        params.setStartSheetIndex(sheetIndexFrom);
        params.setSheetNum(sheetNum);
        params.setTitleRows(titleRow);
        params.setVerifyHandler(verifyHandler);
        ExcelImportResult<T> result = ExcelImportUtil.importExcelMore(
                new File(filePath),
                clz, params);
        return result;
    }

    /**
     * 泛型继承多个接口，进行抽象
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T extends IExcelDataModel & IExcelModel> String generateSheetErrorInfoByFailList(List<T> list) {
        return list.stream().map(b -> String.format("第%d行错误：%s", b.getRowNum() + 1, b.getErrorMsg())).collect(Collectors.joining("\n"));
    }
}
